import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login.vue'
import Home from '../views/Home.vue'
import index from '../views/index.vue'
import pub from '../util/public'
// 引入nprogress进度条
import NProgress from 'nprogress'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
      // 这也是个路由记录
      { path: 'index', component: index }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  // 404页面
  {
    path: '/404',
    name: 'notFound',
    component: () => import(/* webpackChunkName: "about" */ '../views/404.vue')
  },
  {
    path: '*', // 此处需特别注意置于最底部
    redirect: '/404'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  NProgress.start()

  const token = pub.getToken()
  console.log(to.name)
  if (to.name !== 'Login' && !token) {
    console.log('跳转到登录页啦')
    // 跳转登录页
    next('/login')
  }
  next()
})
router.afterEach(() => {
  NProgress.done()
})

export default router
